<template>
  <div>
    <!-- 档案管理 -->
    <el-card class="card">
      <div class="userInfo_box">
        <img
          :src="
            elderlyInfo.photo
              ? imgUrl + elderlyInfo.photo
              : 'http://123.57.237.81:8080/caresystem/upload/2024/11/26/20241126195954213.jpg'
          "
          style="width: 50px; height: 50px"
          alt=""
        />
        <div class="content">
          <div class="content_item">
            <span class="name">老人姓名：</span>
            <span>{{ elderlyInfo.name }}</span>
          </div>
          <div class="content_item">
            <span class="name">身份证/护照号：</span>
            <span>{{ elderlyInfo.idCard }}</span>
          </div>
          <div class="content_item">
            <span class="name">床位号：</span>
            <span>{{ elderlyInfo.begName }}</span>
          </div>
        </div>
      </div>
    </el-card>
    <!-- 表格 -->
    <el-card class="card">
      <el-table :data="filesData" style="width: 100%">
        <el-table-column prop="id" label="序号" width="80" />
        <el-table-column prop="name" label="项目" width="180" />
        <el-table-column label="文件">
          <template #default="scope">
            <el-dropdown v-for="(item, index) in scope.row.files">
              <span class="el-dropdown-link">
                <el-image
                  preview-teleported
                  :preview-src-list="[imgUrl + item.fileName]"
                  :src="imgUrl + item.fileName"
                  style="width: 30px; height: 30px; margin-right: 10px"
                />
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item style="color: #5a92dc" @click="downLoad(item.fileName)">
                    下载
                  </el-dropdown-item>
                  <el-dropdown-item style="color: red" @click="del(item.id, scope.$index, index)">
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <!-- 图片上传 -->
            <el-upload
              :headers="headers"
              class="avatar-uploader"
              :action="BaseUrl + '/api/upload/add'"
              :show-file-list="false"
              :on-success="
                (response) => handleAvatarSuccess(response, scope.$index, scope.row.name)
              "
              :before-upload="beforeAvatarUpload"
            >
              <div class="uploadContent">
                <div class="btns">
                  <el-button type="primary" link>上传文件</el-button>
                </div>
                <div />
              </div>
            </el-upload>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import ELTable, { TableData } from "@/components/ELTable.vue";
import { useRoute } from "vue-router";
import {
  getFileitems,
  getElderlyModel,
  addElderlyFiles,
  getElderlyFilesList,
  delElderlyFiles,
  downFile,
} from "@/api/market/elderly/elderly";
import { onMounted, reactive, ref } from "vue";
import { UploadProps } from "element-plus";
import { CompressImage } from "@/utils/imageUtils";
import { AddElderlyFilesParams, ListElderlyFileParams } from "@/api/market/elderly/type";
import { downloadFile } from "@/utils/downFileUtils";

const route = useRoute();

//根路径
const BaseUrl = import.meta.env.VITE_APP_API_URL;
// 图片根路径
const imgUrl = ref(import.meta.env.VITE_IMG_URL);
const headers = { Authorization: localStorage.getItem("token") };

let filesData = ref<ListElderlyFileParams[]>([]);

//获取档案文件
const getFileitemsData = async (id: number) => {
  let res = await getFileitems();
  filesData.value = res.list;

  //获取老人档案列表
  let fileRes = await getElderlyFilesList(id);
  filesData.value.forEach((item) => {
    item.files = fileRes.list.filter((fItem) => item.name == fItem.name);
  });
};

export interface ElderlyData {
  photo?: string;
  name?: string;
  idCard?: string;
  begName?: string;
}

const elderlyInfo = reactive<ElderlyData>({});

//获取老人详情
const getElderlyDetail = async (id: number) => {
  let res = await getElderlyModel(id);
  Object.assign(elderlyInfo, res);
};

//文件上传前回调
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  let url = URL.createObjectURL(rawFile);
  return CompressImage(url, 50);
  // return true
};

//添加参数
const addFileParams = reactive<AddElderlyFilesParams>({
  elderlyId: Number(route.query.id),
  name: "",
  fileName: "",
});

//文件上传
const handleAvatarSuccess = async (response: any, index: number, name: string) => {
  if (response.code == 10000) {
    addFileParams.name = name;
    addFileParams.fileName = response.data.url;

    let res = await addElderlyFiles(addFileParams);
    if (filesData.value[index].files) {
      filesData.value[index].files?.push(res);
    } else {
      filesData.value[index].files = [res];
    }
  }
};

//删除
const del = (id: number, index: number, fIndex: number) => {
  ElMessageBox.confirm("是否确认删除", "删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await delElderlyFiles(Number(route.query.id), id);
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      //刷新
      filesData.value[index].files?.splice(fIndex, 1);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消 canceled",
      });
    });
};

//下载
const downLoad = async (fileName: string) => {
  let res = await downFile(fileName);
  // console.log("下载", res);

  downloadFile(fileName, res);
};

onMounted(() => {
  if (route.query.id) {
    getElderlyDetail(Number(route.query.id));
    getFileitemsData(Number(route.query.id));
  }
});
</script>

<style scoped>
.card {
  width: 98%;
  margin: 0 auto;
  margin-top: 10px;

  .userInfo_box {
    display: flex;

    img {
      margin-top: 10px;
    }

    .content {
      margin-left: 55px;

      .content_item {
        margin-bottom: 10px;

        .name {
          display: inline-block;
          width: 160px;
        }
      }
    }
  }
}
</style>
